<template lang="pug">
  div.mn
    top-banner
    div.form-w
      div.form-mn
        el-form.loginForm(v-bind:model="loginForm" v-bind:rules="rules" ref="loginForm"
        v-bind:show-message="false")
          div.error-message() {{error.message}}
          el-form-item.kalix-form-item(prop="name")
            el-input(v-model="loginForm.name" placeholder="账号" ref="loginFormName")
              i.icon-user(slot="prefix")
          el-form-item.kalix-form-item(prop="pass")
            el-input(type="password" v-model="loginForm.pass" ref="loginFormPass" placeholder="密码" auto-complete="off")
              i.icon-lock(slot="prefix")
          el-form-item.kalix-form-item
            el-button.btn-submit(type="primary" v-on:click="onSubmit()" size="large") 登录
</template>

<script type="text/ecmascript-6">
import TopBanner from '../components/TopBanner'
import Login from 'comm/login'
import {mapActions} from 'vuex'

export default {
  name: 'LoginForm',
  data() {
    return {
      loginForm: {
        name: '',
        pass: '',
        validateCode: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 12, message: '用户名长度在 2 到 8 个字符', trigger: 'blur'}
        ],
        pass: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        validateCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {validator: this.checkCode, trigger: 'blur'}
        ]
      },
      error: {
        flag: false,
        message: ''
      },
      validateCode: ''
    }
  },
  activated() {
    this.loginForm = {name: '', pass: ''}
    console.log('this.$KalixEventBus', this.$KalixEventBus)
  },
  mounted() {
  },
  methods: {
    ...mapActions(['setAccessToken', 'setCurrentUser', 'setLastLoginTime']),
    checkCode(rule, value, callback) {
      if (this.$refs.elValidateCode.validate()) {
        callback()
      } else {
        callback(new Error('请输入正确的验证码!'))
      }
    },
    onSubmit(formName) {
      if (this._validateForm()) {
        this.login()
      }
    },
    async login() {
      //  登录
      let {code, data} = await Login.remoteLogin({
        'username': this.loginForm.name,
        'password': this.loginForm.pass
      })
      console.log('code:', code)
      console.log('data:', data)
      if (data.success) {
        this.setAccessToken(data.access_token)
        this.setCurrentUser(data.user)
        this.setLastLoginTime(new Date().getTime())
        this.$router.push({path: '/'})
      } else {
        this.$refs.loginFormName.focus()
      }
    },
    _validateForm() {
      //  验证表单
      for (let key in this.rules) {
        this.error.flag = false
        this.error.message = ''
        this.$refs.loginForm.validateField(key, errorMessage => {
          //  如果错误信息长度 > 0 表示验证不通过
          this.error.flag = errorMessage.length > 0
          this.error.message = errorMessage
        })
        if (this.error.flag) {
          return false
        }
      }
      return true
    },
    tabInput() {
      let ipts = document.getElementsByClassName('el-input__inner')
      for (let i = 0; i < ipts.length; i++) {
        ipts[i].addEventListener('keydown', e => {
          if (e.keyCode === 13) {
            if (ipts[i + 1]) {
              ipts[i + 1].focus()
            } else {
              document.getElementsByClassName('btn-submit')[0].focus()
            }
          }
        })
      }
    },
    listen() {
      this.error.flag = false
    }
  },
  components: {
    TopBanner
  },
  computed: {},
  watch: {
    loginForm: {
      handler: 'listen',
      // 深度观察
      deep: true
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .form-mn
    margin 50px auto
    width: 280px
  .error-message
    font-size 12px
    color #F56C6C
    line-height 20px
    height 20px
    margin-bottom 10px
</style>
